package com.gitee.wsl.text.marker

import com.gitee.wsl.func.Supplier

/**
 * 给文本区间附加一个Provider，可以执行provider返回一个值或者ValueMarker
 */
class ProviderMarker(
    textStart: Int,
    textEnd: Int,
    override val name: String?,
    private val provider: Supplier<*>?,
    masked: Boolean
) : Marker(textStart, textEnd) {

    val isMasked: Boolean = masked

    constructor(pos: Int, provider: Supplier<*>, masked: Boolean) : this(
        pos,
        pos + 1,
        null,
        provider,
        masked
    )

    override fun offset(offset: Int): ProviderMarker {
        if (offset == 0) return this
        return ProviderMarker(textBegin + offset, textEnd + offset, name, provider, isMasked)
    }


    override fun toString(): String {
        val sb = StringBuilder()
        return appendPos(sb).append(':').append(name).toString()
    }

    val value: Any?
        get() = provider?.get()

    fun buildValueMarker(): ValueMarker {
        val value = provider?.get()
        return ValueMarker(textBegin, textEnd, name, value, isMasked)
    }

}

fun Marker.Companion.provider(
    textStart: Int,
    textEnd: Int,
    name: String?,
    provider: Supplier<*>?,
    masked: Boolean
): ProviderMarker {
    return ProviderMarker(textStart, textEnd, name, provider, masked)
}